import { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import moment from 'moment';
import { cloneDeep } from 'lodash';
import { Card, Button, Checkbox, Toast, Dialog, InfiniteScroll, SpinLoading } from 'antd-mobile';
import { TextWidget, getMessage } from '@inbiz/react';
import { getEditor } from '@inbiz/utils';
import NoData from '../NoData/ListNoData';
import { toggleSelect, getFormData } from '../utils';
import { removeAssign, getAssignList } from './service';
import { getSummary } from '../../commonUtils';
import './index.less';

const ProcessAssign = forwardRef((props: any, ref) => {
  const { userInfo, rangeConfig, processGroup } = props;
  const [selectItem, setSelectItem] = useState<any[]>([]);
  const [assignedData, setAssignedData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [page, setPage] = useState(1);
  const isEditor = getEditor();

  let pageCheck = null;

  const formatServer = (
    pageIndex: number,
    data: {
      total: number; rows: any[]
    } = { rows: [], total: 0 },
  ) => {
    const state = data !== null;
    let row: any[] = [];
    let checkDataIsNull: boolean | number = false;
    let changeArr: any[] = [];
    let isAdd = false;

    const nowPage = pageIndex;
    if (state) {
      // 判断请求是否成功
      row = data.rows.map((item) => {
        return {
          ...item,
          summary:
            item.summary && item.summary.startsWith('<')
              ? getSummary(item.summary)
              : item.summary,
        };
      });
      checkDataIsNull = row.length && row.length < 1; // 判断是否有数据
      pageCheck = () => {
        // 处理数据
        if (checkDataIsNull) {
          setHasMore(false);
        } else {
          const more = pageIndex < Math.ceil(data.total / 20);
          changeArr = row;
          setHasMore(more);
          setPage(nowPage + 1);
        }
      };
      // 判断页面为1
      if (nowPage == 1) {
        pageCheck();
      } else {
        isAdd = true;
        pageCheck();
      }
      if (isAdd) {
        // 判断是不是有分页数据
        let _assignedData = assignedData;
        setAssignedData([..._assignedData, ...changeArr])
        setSelectItem([..._assignedData, ...changeArr])
      } else {
        setAssignedData(changeArr);
        setSelectItem(changeArr);
      }
    } else {
      if (pageIndex == 1) {
        setAssignedData([]);
        setSelectItem([]);
      }
    }
  };

  const getList = async (
    value: string,
    pageIndex: number,
    searchC?: any,
  ) => {
    setLoading(true);
    const drparams = getFormData(userInfo, pageIndex, value, searchC);
    let res = await getAssignList({
      ...drparams,
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    });
    formatServer(pageIndex, res?.details);
    setLoading(false);
  };

  const changeBox = (checked: boolean, item: { processInstanceId: string }) => {
    const newArr = cloneDeep(selectItem);
    const index = newArr.findIndex((ele: { processInstanceId: string; }) => item.processInstanceId == ele.processInstanceId);
    newArr[index].checked = checked;
    setSelectItem(newArr);
  };

  const cancelAssign = () => {
    const items = selectItem.filter((item: any) => item.checked);
    if (items.length == 0) {
      return Toast.show({ content: getMessage('processCenter.selectOneData') });
    }
    const delegateIds = items.map((ele: any) => ele.Id).join(',');
    const params = new FormData();
    params.append('delegateIds', delegateIds);
    params.append('handelUserId', userInfo.ID);
    Dialog.confirm({
      content: getMessage('processCenter.confirmCancelAssign'),
      onConfirm: () => {
        setLoading(true);
        removeAssign(params).then(async (res) => {
          if (res.isSuccess) {
            await getList('', 1);
          }
          setLoading(false);
        }).catch((error) => { setLoading(false); });
      },
    });
  };

  useEffect(() => {
    getList('', 1);
  }, []);

  useImperativeHandle(ref, () => ({
    getList: async (text: string, condition?: any) => {
      getList(text, 1, condition);
    },
  }));

  return (
    <div className={'processAssign'}>
      {loading ? (
        <div className={'loading'}>
          <SpinLoading />
        </div>
      ) : assignedData.length > 0 ? (
        <>
          {assignedData.map((item: any, index: number) => {
            return (
              <Card
                className={'assignContainer'}
                title={item.stepName}
                key={item.processInstanceId}
                extra={
                  <Checkbox
                    checked={
                      selectItem.find((ele: any) => item.processInstanceId == ele.processInstanceId)
                        ?.checked || false
                    }
                    onChange={(checked) => changeBox(checked, item)}
                  />
                }
              >
                <section
                  style={{ display: 'flex' }}
                // onClick={() => clickApply(item.Incident_ID)}
                >
                  <p className={'contentBody'}>
                    <p title={item.initiatorName}>
                      <TextWidget>processCenter.starter</TextWidget>: {item.initiatorName}
                    </p>
                    <p title={item.processInstanceId}>
                      <TextWidget>processCenter.instanceNumber</TextWidget>:{' '}
                      {item.processInstanceId}
                    </p>
                  </p>
                  <p className={'contentBody'}>
                    <p title={item.Assignment}>
                      <TextWidget>processCenter.assigner</TextWidget>: {item.Assignment}
                    </p>
                    <p title={item.processName}>
                      <TextWidget>processCenter.taskProcess</TextWidget>: {item.processName}
                    </p>
                  </p>
                </section>
                <footer
                  style={{
                    display: 'flex',
                    flexDirection: 'row-reverse',
                    paddingBottom: 12,
                    fontSize: 12,
                  }}
                >
                  <p style={{ marginBottom: 0 }}>
                    {moment(item.taskCreateTime).format('YYYY-MM-DD HH:mm:ss')}
                  </p>
                </footer>
              </Card>
            );
          })}
          <InfiniteScroll loadMore={() => getList('', page)} hasMore={hasMore} />
          <footer className={'operationFooter'} style={{ width: isEditor ? '19.5%' : '100%' }}>
            <div>
              {selectItem.filter((item: { checked: boolean }) => item.checked).length !==
                selectItem.length && (
                  <Button
                    color="primary"
                    fill="none"
                    onClick={() => toggleSelect(true, assignedData, setSelectItem)}
                  >
                    <TextWidget>processCenter.selectAll</TextWidget>
                  </Button>
                )}
              {selectItem.filter((item: { checked: boolean }) => item.checked).length ==
                selectItem.length && (
                  <Button
                    color="primary"
                    fill="none"
                    onClick={() => toggleSelect(false, assignedData, setSelectItem)}
                  >
                    <TextWidget>processCenter.cancelSelectAll</TextWidget>
                  </Button>
                )}
              {Boolean(selectItem.filter((item: { checked: boolean }) => item.checked).length) && (
                <span className={'selectedNumber'}>
                  <TextWidget>processCenter.haveselected</TextWidget>
                  {selectItem.filter((item: { checked: boolean }) => item.checked).length}
                  <TextWidget>processCenter.item</TextWidget>
                </span>
              )}
            </div>
            <div>
              <Button
                color="primary"
                onClick={cancelAssign}
                disabled={selectItem.filter((item: any) => item.checked).length == 0}
              >
                <TextWidget>processCenter.cancelAssign</TextWidget>
              </Button>
            </div>
          </footer>
        </>
      ) : (
        <NoData />
      )}
    </div>
  );
})

export default ProcessAssign;
